package io.hei.modules.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ChannelHandler.Sharable
public class ChatChannelHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private static final Map<String, Channel> users = new ConcurrentHashMap();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg){

        Channel incoming = ctx.channel();
        String uName = msg.text().substring(0, msg.text().indexOf(":"));
        String content = msg.text().substring(msg.text().indexOf(":") + 1);
        for (Channel channel : channels) {
            if (channel != incoming){
                channel.writeAndFlush(new TextWebSocketFrame("【" + uName + "】" + content));
            } else {
                channel.writeAndFlush(new TextWebSocketFrame("【我】" + content));
            }
        }
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        System.out.println(ctx.channel().remoteAddress());
        String uName = ctx.channel().id().asShortText();  //用来获取一个随机的用户名，可以用其他方式代替
        for (Channel channel : channels) {
            channel.writeAndFlush(new TextWebSocketFrame("【新用户】 - " + uName + " 加入"));
        }
        channels.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        String uName = ctx.channel().id().asShortText();
        for (Channel channel : channels) {
            channel.writeAndFlush(new TextWebSocketFrame("【用户】 - " + uName + " 离开"));
        }
        channels.remove(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println(cause.getMessage());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("用户:"+ctx.channel().id().asShortText()+"在线");
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("用户:"+ctx.channel().id().asShortText()+"掉线");
    }
}